package cn.vivi.seckill.interceptor;

import cn.vivi.seckill.pojo.User;
import cn.vivi.seckill.service.UserService;
import cn.vivi.seckill.util.CookieUtils;
import cn.vivi.seckill.util.JsonUtils;
import cn.vivi.seckill.vo.RespBean;
import cn.vivi.seckill.vo.RespBeanEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class WebInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override // 判断用户是否登陆的拦截逻辑
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtils.getCookieValue(request, "userTicket");
        if (StringUtils.isEmpty(ticket)) {
            JsonUtils.toJson(response.getOutputStream(), RespBean.error(RespBeanEnum.USER_NO_LOGIN));
            return false;
        }
        User user = userService.getUserByCookie(ticket, request, response);
        if (Objects.isNull(user)) {
            JsonUtils.toJson(response.getOutputStream(), RespBean.error(RespBeanEnum.USER_NO_LOGIN));
            return false;
        }
        return true;
    }
}
